package com.rp.article.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.rp.article.serivce.ArticlePortalService;
import com.rp.news.common.PagedResult;
import com.rp.news.common.RedisCommon;
import com.rp.news.common.Result;
import com.rp.news.util.IPUtil;
import com.rp.news.util.RedisOperator;
import com.rp.pojo.Article;
import com.rp.vo.AppUserVo;
import com.rp.vo.ArticleDetailVO;
import com.rp.vo.IndexArticleVO;
import com.rp.vo.QueryAllListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@Slf4j
@Api(value = "门户文章业务controller", tags = {"门户文章业务controller"})
@RequestMapping("portal/article")
public class ArticlePortalController {

    @Autowired
    private ArticlePortalService articlePortalService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    public RedisOperator redis;


    @PostMapping("/list")
    @ApiOperation(value = "管理员查询用户的所有文章列表", notes = "管理员查询用户的所有文章列表")
    public Result queryAllList(@RequestBody @Valid QueryAllListVo vo) {
        log.info("管理员查询用户的所有文章列表,请求参数 vo = {}", JSONUtil.toJsonStr(vo));
        PagedResult pagedResult = articlePortalService.queryIndexArticleList(vo);
        log.info("管理员查询用户的所有文章列表 pagedResult = {}", JSONUtil.toJsonStr(pagedResult));

        List<Article> rows = (List<Article>) pagedResult.getRows();
        Set<String> idSet = new HashSet<>();

        List<String> idList = new ArrayList<>();
        if (CollUtil.isNotEmpty(rows)) {
            rows.forEach(item ->{
                idSet.add(item.getPublishUserId());
                //构建文章id的list
                idList.add(RedisCommon.REDIS_ARITCLE_READ_COUNTS + item.getId());
            });
        }
        //
        log.info("idlist 的 值为 {}",JSONUtil.toJsonStr(idList));
        List<String> readCountList = redis.mget(idList);
        log.info("从redis中获取的数据 readCountList = {}", JSONUtil.toJsonStr(readCountList));

        //发起远程请求(resttemplate) ,请求用户服务获取用户(idset 发布者) 的列表
        List<AppUserVo> appUserVoList = getPublisherList(idSet);
        log.info("发起远程请求(resttemplate) ,请求用户服务获取用户(idset 发布者) 的列表,返回结果 appUserVoList = {}",JSONUtil.toJsonStr(appUserVoList));
        //拼接连个list 重组文章列表

        List<IndexArticleVO> result = new ArrayList<>();
        for (int i = 0; i < rows.size(); i++) {
            Article article = rows.get(i);
            IndexArticleVO convert = Convert.convert(IndexArticleVO.class, article);
            AppUserVo userIfPublisher = getUserIfPublisher(article.getPublishUserId(), appUserVoList);
            convert.setPublisherVO(userIfPublisher);

            String s = readCountList.get(i);
            int readCount = 0;
            if (StrUtil.isNotBlank(s)) {
                readCount = Integer.valueOf(s);
            }
            convert.setReadCounts(readCount);

            result.add(convert);
        }

        return Result.ok(result);
    }

    private List<AppUserVo> getPublisherList(Set<String> idSet) {
        log.info("getPublisherList-idSet  = {}",JSONUtil.toJsonStr(idSet));
        String url = "http://www.rpnews.com:7007/userservice/user/queryByIds?userIds=" + JSONUtil.toJsonStr(idSet);
        log.info("getPublisherList = url = {}",url);
        ResponseEntity<Result> forEntity = restTemplate.getForEntity(url, Result.class);
        log.info("getPublisherList,远程请求返回结果 forEntity = {}",forEntity);
        Result body = forEntity.getBody();
        List<AppUserVo> appUserVoList = new ArrayList<>();
        if (body.getStatus() == 200) {
            Object data = body.getData();
            appUserVoList = Convert.convert(new TypeReference<List<AppUserVo>>() {
            }, data);
        }
        return appUserVoList;
    }

    @GetMapping("/hotList")
    @ApiOperation(value = "首页查询热闻列表", notes = "首页查询热闻列表", httpMethod = "GET")
    public Result hotList() {
        List<Article> list = articlePortalService.queryHotList();
        return Result.ok(list);
    }

    @GetMapping("/queryArticlListOfWriter")
    @ApiOperation(value = "查询作家发布的所有文章列表", notes = "查询作家发布的所有文章列表", httpMethod = "GET")
    public Result queryArticlListOfWriter(String writerId, Integer page, Integer pageSize) {

        PagedResult result = articlePortalService.queryArticlListOfWriter(writerId, page, pageSize);
        return Result.ok(result);
    }

    @GetMapping("/queryGoodArticlListOfWriter")
    @ApiOperation(value = "作家页面查询近期佳文", notes = "作家页面查询近期佳文", httpMethod = "GET")
    public Result queryGoodArticlListOfWriter(String writerId) {
        PagedResult result = articlePortalService.queryGoodArticlListOfWriter(writerId);
        return Result.ok(result);
    }

    @GetMapping("/detail")
    @ApiOperation(value = "文章详情查询", notes = "文章详情查询", httpMethod = "GET")
    public Result detail(String articleId) {
        ArticleDetailVO vo = articlePortalService.detail(articleId);
        Set<String> sets = new HashSet<>();
        sets.add(vo.getPublishUserId());

        List<AppUserVo> publisherList = getPublisherList(sets);
        if (CollUtil.isNotEmpty(publisherList)) {
            vo.setPublishUserName(publisherList.get(0).getNickname());
        }
        vo.setReadCounts(redis.getCountsFromRedis(RedisCommon.REDIS_ARITCLE_READ_COUNTS + vo.getId()));
        return Result.ok(vo);
    }

    @PostMapping("/readArticle")
    @ApiOperation(value = "阅读文章,文章阅读累加1", notes = "阅读文章,文章阅读累加1", httpMethod = "POST")
    public Result readArticle(String articleId, HttpServletRequest request) {
        String requestIp = IPUtil.getRequestIp(request);
        //设置带给你钱用户ip的永久key,永久存放在redis\中,表示该文章已经阅读过了
        redis.setnx(RedisCommon.REDIS_ALREADY_READ + articleId + ":" + requestIp, requestIp);
        redis.increment(RedisCommon.REDIS_ARITCLE_READ_COUNTS + articleId, 1);
        return Result.ok();
    }

    @GetMapping("/readCounts")
    @ApiOperation(value = "获取文章阅读数", notes = "获取文章阅读数", httpMethod = "GET")
    public Integer readCounts(String articleId) {
        Integer countsFromRedis = redis.getCountsFromRedis(RedisCommon.REDIS_ARITCLE_READ_COUNTS + articleId);
        return countsFromRedis;
    }


    private AppUserVo getUserIfPublisher(String publishId, List<AppUserVo> list) {
        for (int i = 0; i < list.size(); i++) {
            AppUserVo appUserVo = list.get(i);
            boolean equal = ObjectUtil.equal(appUserVo.getId(), publishId);

            if (equal) {
                return appUserVo;
            }
        }
        return null;
    }
}
